package com.wen.controller;


import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.lang.Assert;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.wen.common.lang.Result;
import com.wen.entity.Blog;
import com.wen.service.BlogService;
import com.wen.util.ShiroUtil;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresAuthentication;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author xiaotian
 * @since 2022-04-18
 */
@RestController
public class BlogController {

    @Autowired
    BlogService blogService;

    //列表
    //@RequestParam(defaultValue = "1") 默认为1页
    @GetMapping("/blogs")
    public Result list(@RequestParam(defaultValue = "1") Integer currentPage){
        Page page = new Page(currentPage,5);
        IPage pageData = blogService.page(page, new QueryWrapper<Blog>().orderByDesc("created"));
        return Result.success(pageData);
    }
    //摘通过id返回对应博客
    @GetMapping("/blog/{id}")
    public Result detail(@PathVariable(name = "id") Long id){
        Blog blog  = blogService.getById(id);
        //判断id是否为空，为空则断言异常
        Assert.notNull(blog,"该博客已被删除");
        return Result.success(blog);
    }

    //编辑
    @RequiresAuthentication //需要认证才能编辑
    @PostMapping("/blog/edit")
    //@Validated 校验
    //@RequestBody 请求体获取参数
    public Result edit(@Validated @RequestBody Blog blog){
        //一个空对象用于赋值
        Blog temp = null;
        //先判断是否有该博客的id，有则是编辑，没有则是创建
        if(blog.getId() != null){
            //将数据库的内容传递给temp
            temp = blogService.getById(blog.getId());
            //只能编辑自己的文章
            //ShiroUtil:自己写的util工具，获取传入的数据id
            Assert.isTrue(temp.getUserId().longValue() == ShiroUtil.getProfile().getId().longValue(),"没有权限编辑");
        }else{
            temp = new Blog();
            temp.setUserId(ShiroUtil.getProfile().getId());
            temp.setCreated(LocalDateTime.now());
            temp.setStatus(0);
        }
//        System.out.println("blog============"+blog);
//        System.out.println("temp====================="+temp);
        //将blog的值复制给temp 复制的时候忽略 "id","userid","created","status"四个字段
        BeanUtil.copyProperties(blog,temp,"id","userId","created","status");
//        System.out.println("blog,after============"+blog);
//        System.out.println("temp,after====================="+temp);
        blogService.saveOrUpdate(temp);

        return Result.success(null);
    }

    //@PathVariable 动态路由：将url中的id传入方法参数
    @RequiresAuthentication //需要认证后才能删除
    @PostMapping("/blogdel/{blog_id}")
    public Result delete(@PathVariable Long blog_id){
        boolean b = blogService.removeById(blog_id);
        //判断是否为空，为空则断言异常
        if (b == true){
            return Result.success("文章删除成功");
        }else{
            return Result.fail("文章删除失败");
        }
    }


}
